package com.hyl.crmclient.config.shiro;

import com.hyl.crmclient.service.UserService;
import com.hyl.jpademo.entity.Right;
import com.hyl.jpademo.entity.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.Set;

/**
 * @Description TODO
 * @Author hyl
 * @Date 2022/6/13 9:36
 **/
public class MyShiroRealm extends AuthorizingRealm {

	@Resource
	private UserService userService;

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authenticationToken) throws AuthenticationException {
		System.out.println("进入认证。。。");
		//1、验证账户是否被锁定==》lock ==》抛异常
		//2、判断账户验证的次数是否超多5次
		//  超过==》修改账户的状态==》删除登入的次数  ==》抛异常
		//  不超过==》增加账户登入次数/验证次数
		//3、数据校验

		//口令
		UsernamePasswordToken token  = (UsernamePasswordToken) authenticationToken;
		//获取登入用户的用户名和密码
		String name = token.getUsername();
		//根据用户名，获取登入用户信息
		User user = userService.findByUsername(name);
		//不存在
		if(user==null){
			throw  new UnknownAccountException("用户名错误");
		}
		//逻辑：账号被锁
		if(user.getUsrFlag()==null || user.getUsrFlag().intValue() == 0){
			throw new LockedAccountException("账号锁定，请联系管理员");
		}
		try {
			SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
					user,  //身份
					user.getUsrPassword(), //凭证，密码
					ByteSource.Util.bytes("czkt"), //加密使用的 salt
					getName()); //realm名称
			//4、验证通过==》删除登入次数
			return authenticationInfo;
		}catch (Exception e){
			e.printStackTrace();
		}
		return null;

	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		System.out.println("授权。。。");
		//身份
		User user = (User) principalCollection.getPrimaryPrincipal();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		//角色
		info.addRole(user.getRole().getRoleName());
		//判断角色==》不同的角色，设置不同的权限
		Set<Right> rights = user.getRole().getRights();//权限
		for(Right tmp : rights){
			if(tmp.getRightUrl()!=null && !tmp.getRightUrl().equals("") ) {
				info.addStringPermission(tmp.getRightCode());
			}
		}

//		if (user.getRole().getRoleName().equals("管理员")) {
//			info.addStringPermission("销售机会列表");
//			info.addStringPermission("销售机会编辑");
////			info.addStringPermission("销售机会新增");
//		}else{
//			info.addStringPermission("销售机会列表");
//		}

		return info;
	}


}
